package com.jingge.autojob.skeleton.model.task.remote;

import com.jingge.autojob.util.http.HttpUtil;
import okhttp3.Response;
import okhttp3.ResponseBody;

import java.io.Closeable;
import java.io.InputStream;

/**
 * @author JingGe(* ^ ▽ ^ *)
 * @date 2023-09-04 15:50
 * @email 1158055613@qq.com
 */
public class HttpRemoteResponse implements RemoteResponse, Closeable {
    private transient final Response response;

    public HttpRemoteResponse(Response response) {
        this.response = response;
    }

    @Override
    public boolean isSuccess() {
        return response != null && response.code() == 200;
    }

    @Override
    public long getResponseLength() {
        ResponseBody body = response.body();
        if (body != null) {
            return body.contentLength();
        }
        return -1;
    }

    @Override
    public InputStream getAsInputStream() {
        return HttpUtil.getResponseAsInputStream(response);
    }

    @Override
    public <T> T getAsObject(Class<T> type) {
        return HttpUtil.getResponseAsInstance(response, type);
    }

    @Override
    public String getAsString() {
        return HttpUtil.getResponseAsString(response);
    }

    @Override
    public Object getAsObject() {
        throw new UnsupportedOperationException();
    }

    @Override
    public void close() {
        if (response != null) {
            try {
                response.close();
            } catch (Exception ignored) {
            }
        }
    }

    @Override
    public String toString() {
        return getAsString();
    }
}
